package civicinity.ist.psu.edu.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.events.CivicinityEventParticipate;
import civicinity.ist.psu.edu.share.CivicinityMyView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

public class CivicinityCameraMode extends Activity {
	
	protected static final int PHOTO_CAPTURE_CODE = 0;
	private String mCameraImageID;
	private int mPreviousActivity = 0;
	private int mEventID;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    Intent gIntent = getIntent();
	    mPreviousActivity = gIntent.getExtras().getInt("prev_activity");
	    if(mPreviousActivity == Constants.PREV_ACITIVITY_EVENT) {
	    	mEventID = gIntent.getExtras().getInt("event_id");
	    }
	    
	    // check sd card
	    checkSDCard();
	    // TODO Auto-generated method stub
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	private void checkSDCard() {
		try {
			File ld = new File(Constants.CIVICINITY_PHOTO_PATH);
			
			if(ld.exists()) {
				if (!ld.isDirectory()) {
					Toast.makeText(CivicinityCameraMode.this, "Error: Please check your sdcard.", Toast.LENGTH_SHORT).show();
					finish();
				}
			}
			else {
				ld.mkdir();
			}
			
			try {
				SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
				String randomNum = new Integer(prng.nextInt()).toString();
				MessageDigest sha = MessageDigest.getInstance("SHA-1");
				byte[] result = sha.digest(randomNum.getBytes());
				mCameraImageID = hexEncode(result);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			
			Intent mediaCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			mediaCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
					Uri.fromFile(new File(Constants.CIVICINITY_PHOTO_PATH, mCameraImageID + ".jpg")));
			startActivityForResult(mediaCaptureIntent, PHOTO_CAPTURE_CODE);
			
		}
		catch (Exception e) {
			Log.e("K", e.toString());
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// You can use the requestCode to select between multiple child
		// activities you may have started. Here there is only one thing
		// we launch.
		
		Log.i("K", "resultCode : " + resultCode);
	
		if(resultCode == Activity.RESULT_OK) {
			
			Log.i("K", "requestCode : " + requestCode);
			
			if (requestCode == PHOTO_CAPTURE_CODE) {
				Toast.makeText(this, "Photo added!", Toast.LENGTH_SHORT).show();
				
				//Log.i("K","CAMERA_IMAGE_ID : " + mCameraImageID);
				//Bitmap resizedPhoto = ShowPhotoTaken(Constants.CIVICINITY_PHOTO_PATH + mCameraImageID + ".jpg");
				
				String imagePath = Constants.CIVICINITY_PHOTO_PATH + mCameraImageID + ".jpg";
				
				if(mPreviousActivity == Constants.PREV_ACITIVITY_SHARE) {
					Intent intent = new Intent(CivicinityCameraMode.this, CivicinityMyView.class);
					intent.putExtra("image_path", imagePath);
					startActivity(intent);
				}
				else if(mPreviousActivity == Constants.PREV_ACITIVITY_EVENT) {
					Intent intent = new Intent(CivicinityCameraMode.this, CivicinityEventParticipate.class);
					intent.putExtra("image_path", imagePath);
					intent.putExtra("event_id", mEventID);
					startActivity(intent);
				}

				finish();
			}
		}		
		else if(resultCode == Activity.RESULT_CANCELED) {
			finish();
		}
	}
	
	static private String hexEncode(byte[] aInput){
		StringBuilder result = new StringBuilder();
		char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m'};
		for ( int idx = 0; idx < 5; ++idx) {
			byte b = aInput[idx];
			result.append( digits[ (b&0xf0) >> 4 ] );
			result.append( digits[ b&0x0f] );
		}
		return result.toString();
	}
}
